package main

import (
	"encoding/xml"
	"fmt"
	"strings"
)

/*
<xml>
	<ToUserName><![CDATA[toUser]]></ToUserName>
	<FromUserName><![CDATA[fromUser]]></FromUserName>
	<CreateTime>1348831860</CreateTime>
	<MsgType><![CDATA[text]]></MsgType>
	<Content><![CDATA[this is a test]]></Content>
	<MsgId>1234567890123456</MsgId>
</xml>
*/

// CharData is a string that should be cdata-wrapped according to the VAST 3 spec.
type CharData string

// MarshalXML implements the xml.Marshaler interface for generating XML.
func (cd CharData) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
	return e.EncodeElement(struct {
		S string `xml:",innerxml"`
	}{
		S: "<![CDATA[" + string(cd) + "]]>",
	}, start)
}

type TextMessage struct {
	ToUserName   CharData`xml:"toUserName"`
	FromUserName CharData
	CreateTime   int64
	MsgType      CharData
	Content      CharData
	MsgId        CharData
}

func main() {
	input := `<xml>
	<toUserName><![CDATA[toUser]]></toUserName>
	<FromUserName><![CDATA[fromUser]]></FromUserName>
	<CreateTime>1348831860</CreateTime>
	<MsgType><![CDATA[text]]></MsgType>
	<Content><![CDATA[this is a test]]></Content>
	<MsgId>1234567890123456</MsgId>
</xml>`
	inputReader := strings.NewReader(input)
	decoder := xml.NewDecoder(inputReader)

	textMessage := new(TextMessage)
	decoder.Decode(textMessage)

	fmt.Println(textMessage.Content)
	fmt.Printf("%+v\n", textMessage)

	bs, err := xml.Marshal(*textMessage)
	if err != nil {
		fmt.Println("xx")
	}
	fmt.Println( "<xml>"+string(bs)+"</xml>")
}
